package com.usermanage.util;

import kingdee.bos.webapi.client.K3CloudApiClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by  on 2018/12/25
 * 金蝶单位数据
 */
@Slf4j
@Component
public class KingDeeUtil {

    /**
     * 保存数据
     *
     * @param client
     * @param formId
     * @param json
     * @return
     */
    public static Map save(K3CloudApiClient client, String formId, String json) {
        Map saveMap = null;
        try {
            //金蝶保存项目数据
            String saveResult = client.save(formId, json);
            //验证保存是否成功
            saveMap = getMapResult(saveResult);
        } catch (Exception e) {
            log.error("******金蝶提交数据异常********" + e);
            saveMap.put("IsSuccess", false);
            saveMap.put("Message", e);
        }
        log.info(">>>>>>>>>>>金蝶保存数据结果<<<<<<<<<<<<"+saveMap);
        return saveMap;
    }


    public static Map view(K3CloudApiClient client, String formId, String id, String number) {
        Map map = new HashMap();
        try {
            if (StringUtils.isNotBlank(id)) {
                map.put("Id", id);
            } else if (StringUtils.isNotBlank(number)) {
                map.put("Number", number);
            } else {
                throw new Exception("数据id和数据编码不能同时为空！");
            }
            //金蝶返回数据
            String kingDeeResult = client.view(formId, StringUtil.ObjectToJson(map));
            //金蝶返回数据转map
            Map kingDeeResultMap = StringUtil.JsonToMap(kingDeeResult);
            //解析金蝶数据，获取一级数据map
            Map firstLevelMap = StringUtil.JsonToMap(StringUtil.ObjectToJson(kingDeeResultMap.get("Result")));
            //解析金蝶数据，获取二级数据map
            map = StringUtil.JsonToMap(StringUtil.ObjectToJson(firstLevelMap.get("Result")));
        } catch (Exception e) {
            log.error("******金蝶查看数据异常********" + e);
        }
        log.info(">>>>>>>>>>>金蝶view数据结果<<<<<<<<<<<<"+map);
        return map;
    }

    /**
     * 查询数据
     *
     * @param client
     * @param formId
     * @param fieldKeys
     * @param filterString
     * @param startRow
     * @param limit
     * @return
     */
    public static List<Map> query(K3CloudApiClient client, String formId, String fieldKeys, String filterString, int startRow, int limit) {
        List<Map> result = null;
        try {
            List<List<Object>> list = client.executeBillQuery(getMapJson(formId, fieldKeys, filterString, startRow, limit));
            if (list != null) {
                String[] fieldkey = fieldKeys.split(",");
                result = new ArrayList<>();
                for (List<Object> listObject : list) {
                    Map map = new HashMap();
                    for (int i = 0; i < listObject.size(); i++) {
                        map.put(fieldkey[i], listObject.get(i));
                    }
                    result.add(map);
                }
            }
        } catch (Exception e) {
            log.info("*****项目列表查询异常******" + e);
        }
        return result;
    }


    /**
     * 提交数据
     *
     * @param client
     * @param formId
     * @param number
     * @return
     */
    public static Map submit(K3CloudApiClient client, String formId, String number) {
        Map map = null;
        try {
            Map submitAndAuditMap = new HashMap();
            submitAndAuditMap.put("Numbers", number);
            submitAndAuditMap.put("CreateOrgId", "0");
            String submitResult = client.submit(formId, StringUtil.ObjectToJson(submitAndAuditMap));
            //验证提交数据是否成功
            map = getMapResult(submitResult);
        } catch (Exception e) {
            log.error("******金蝶提交数据异常********" + e);
            map.put("IsSuccess", false);
            map.put("Message", e);
        }
        log.info(">>>>>>>>>>>金蝶submit数据结果<<<<<<<<<<<<"+map);
        return map;
    }


    /**
     * 审核
     *
     * @param client
     * @param formId
     * @param number
     * @return
     */
    public static Map audit(K3CloudApiClient client, String formId, String number) {
        Map map = null;
        try {
            Map submitAndAuditMap = new HashMap();
            submitAndAuditMap.put("CreateOrgId", "0");
            submitAndAuditMap.put("Numbers", number);
            String auditResult = client.audit(formId, StringUtil.ObjectToJson(submitAndAuditMap));
            //验证提交数据是否成功
            map = getMapResult(auditResult);
        } catch (Exception e) {
            log.error("******金蝶审核数据异常********" + e);
            map.put("IsSuccess", false);
            map.put("Message", e);
        }
        log.info(">>>>>>>>>>>金蝶auditResult数据结果<<<<<<<<<<<<"+map);
        return map;
    }


    /**
     * 验证数据是否存在
     *
     * @param client
     * @param formId
     * @param fieldKeys
     * @param filterString
     * @return
     */
    public static boolean isExist(K3CloudApiClient client, String formId, String fieldKeys, String filterString) {
        try {
            List<List<Object>> material = client.executeBillQuery(getMapJson(formId, fieldKeys, filterString, 0, 0));
            if (material.size() == 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("*****验证金蝶项目是否存在异常*****" + e);
            return false;
        }
    }

    /**
     * 金蝶登陆
     * @return
     * @throws Exception
     */
    public static K3CloudApiClient login(String str) {
        K3CloudApiClient client = null;
        try {
            boolean bool;
            client = new K3CloudApiClient(KingdeeStatic.POST_K3CloudURL);
            switch (str) {
                case "INFORMALITY":
                    bool = client.login(KingdeeStatic.K3CLOUD_DBID_TEST, KingdeeStatic.K3CLOUD_UID, KingdeeStatic.K3CLOUD_PWD_TEST, KingdeeStatic.K3CLOUD_LANG);
                    break;
                case "OFFICIAL":
                    bool = client.login(KingdeeStatic.K3CLOUD_DBID, KingdeeStatic.K3CLOUD_UID, KingdeeStatic.K3CLOUD_PWD, KingdeeStatic.K3CLOUD_LANG);
                    break;
                default:
                    bool = false;
                    break;
            }
            if (!bool) {
                throw new Exception("金蝶登 陆失败！");
            }
        } catch (Exception e) {
            log.error("*****金蝶登陆失败，系统异常信息为******"+e);
        }
        return client;
    }



    private static Map getMapResult(String result) throws Exception {
        Map returnMap = new HashMap();
        Map resultMap = StringUtil.JsonToMap(result);
        Map firstLevelMap = StringUtil.JsonToMap(StringUtil.ObjectToJson(resultMap.get("Result")));
        Map secondLevelMap = StringUtil.JsonToMap(StringUtil.ObjectToJson(firstLevelMap.get("ResponseStatus")));
        if (Boolean.valueOf(secondLevelMap.get("IsSuccess").toString())) {
            returnMap.put("IsSuccess", true);
            returnMap.put("Id", firstLevelMap.get("Id"));
        } else {
            returnMap.put("IsSuccess", false);
            returnMap.put("Message", StringUtil.JsonToList(StringUtil.ObjectToJson(secondLevelMap.get("Errors"))).get(0).get("Message"));
        }
        return returnMap;
    }

    private static String getMapJson(String formId,String fieldKeys,String filterString,int startRow,int limit){
        Map map = new LinkedHashMap();
        map.put("FormId", formId);//业务对象表单Id（必录）
        map.put("FieldKeys", fieldKeys);//需查询的字段key集合，字符串类型，格式："key1,key2,..." （必录），注（查询单据体内码,需加单据体Key和下划线,如：FEntryKey_FEntryId）
        if (StringUtils.isNotBlank(filterString)) {
            map.put("FilterString", filterString);//过滤条件，字符串类型（非必录）
        }
//            map.put("OrderString", "FStockUnitId");//排序字段，字符串类型（非必录）
//        map.put("TopRowCount", "1000000000");//返回总行数，整型（非必录）
        map.put("StartRow", startRow);//开始行索引，整型（非必录）
        map.put("Limit", limit);//最大行数，整型，不能超过2000（非必录）
        return StringUtil.ObjectToJson(map);
    }

}
